import axios from 'axios'
import { Toast } from 'vant'
import { getToken } from '@/utils/storage'
import router from '@/router'

const instance = axios.create({
    baseURL: 'http://toutiao.itheima.net/',
    timeout: 5000
})

// 添加请求拦截器
instance.interceptors.request.use(function(config) {
    config.headers.Authorization = `Bearer ${getToken()}`
    return config
}, function(error) {
    return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use(function(response) {
    return response
}, function(error) {
    if (error.response.status === 401) {
        Toast.fail('请重新登录')
        router.push('/login')
    } else {
        Toast.fail(error.response.data.message)
    }
    return Promise.reject(error)
})

export default instance
